<?php
namespace Modules\Node\Library;

use MongoDB\BSON\ObjectID;

class NodeChosenSource
{
    public static function getOptions($value)
    {
        $user = Di::getDefault()->getShared('entityManager')->get('node', [
            'conditions' => [
                '_id' => new ObjectID($value)
            ]
        ]);
        if (!$user) {
            return [];
        }
        return [
            $value => $user->getTitle()
        ];
    }

    public static function ajaxSource()
    {
        $request = Di::getDefault()->getShared('request');
        $term = $request->getQuery('term');
        $term = urldecode($term);

        if($request->has('contentModel')){
            $contentModel = $request->getQuery('contentModel');
            $contentModel = urldecode($contentModel);
            $term = 'contentModel:'.$contentModel.' '.$term;
        }

        $data = [];
        $search = new Search(WEB_CODE . '_node');
        $searchData = $search->search([
            'conditions' => $term,
            'limit' => [20, 0]
        ]);

        foreach ($searchData as $item) {
            $data[] = [
                'id' => $item->id,
                'name' => $item->getTitle()
            ];
        }
        return $data;
    }
}